package com.lowan.iot.api.sdk.util;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @title: OkHttpUtil.java
 * @author: ysp
 * <p>
 * 提供okHttp请求工具类
 */
@Slf4j
public class OkHttpUtil {

    /**
     * 初始化okHttpClient
     */
    public static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(60000, TimeUnit.MILLISECONDS)
            .readTimeout(60000, TimeUnit.MILLISECONDS)
            .build();

    public static final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

    /**
     * 发送post请求
     *
     * @param URI  请求路径
     * @param body 请求参数体
     */
    public static String post(String URI, Object body) {

        try {

            RequestBody requestBody = RequestBody.create(jsonType, JSONObject.toJSONString(body));
            Request.Builder builder = new Request.Builder().post(requestBody).url(URI);
            Response response = okHttpClient.newCall(builder.build()).execute();
            String result = response.body().string();
            return result;

        } catch (IOException e) {

            log.error("post请求失败，error reason：{}", e.toString());
        }
        return null;

    }
}
